package com.yc.fruitmarket.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class BaseServlet extends HttpServlet {
	
	//servlet 还有三个方法：		init初始化	service分发		destory销毁
	
	//分发
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//首先，我们得到资源路径
		String uri = req.getRequestURI();
		System.out.println(uri);
		String path = uri.substring(uri.lastIndexOf("/") + 1);	//获取路径后方方法
		System.out.println(path);
		
		//获取当前servlet中所有的方法
		Method[] methods = this.getClass().getDeclaredMethods();
		for(Method m : methods) {
			//当path和当前servlet当中所有的方法名比较，有相同时
			if(m.getName().equals(path)) {
				//反向激活方法
				try {
					req.setCharacterEncoding("utf-8");
					resp.setCharacterEncoding("utf-8");
					m.invoke(this, req, resp);
				} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return;
			}
		}
	}
	
	//发送响应给客户端
	protected void send(HttpServletResponse resp, int obj) {
		try {
			PrintWriter out = resp.getWriter();
			out.print(obj);
			out.flush();	//io流
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//方法重载
	protected void send(HttpServletResponse resp, String obj) {
		try {
			PrintWriter out = resp.getWriter();
			out.print(obj);
			out.flush();	//io流
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	protected void send(HttpServletResponse resp, Object obj) {
		try {
			PrintWriter out = resp.getWriter();
			
			Gson gson = new Gson();
			String json = gson.toJson(obj);
			
			out.print(json);
			out.flush();	//io流
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
